package com.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

import com.exception.ErrorCode.FileErrorCode;
import com.exception.FileException;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.annotation.IgnoreAuth;
import com.utils.R;


@RestController
@RequestMapping("file")
@SuppressWarnings({"unchecked", "rawtypes"})
public class FileController {

    /**
     * 上传文件
     */
    @RequestMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        //判断文件是否为空
        if (file.isEmpty()) {
            throw new FileException(FileErrorCode.FILE_IS_NULL);
        }
        //给文件命名
        String fileExt = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        //设置文件的上传路径
        File path = new File(ResourceUtils.getURL("classpath:static").getPath());
        //路径不存在就创建路径
        if (!path.exists()) {
            path = new File("");
        }

        File upload = new File(path.getAbsolutePath(), "/upload/");
        if (!upload.exists()) {
            upload.mkdirs();
        }
        String fileName = new Date().getTime() + "." + fileExt;
        File dest = new File(upload.getAbsolutePath() + "/" + fileName);
        file.transferTo(dest);

        return R.ok().put("file", fileName);
    }


}
